package 多态.向上转移和向下转型.向下转型;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-06-16
 * Time: 21:31
 */
//向下转型用的比较少，而且不安全，万一转换失败，运行时就会抛异常。Java中为了提高向下转型的安全性，引入
//了instanceof ，如果该表达式为true，则可以安全转换。
public class TestAnimal1 {
    public static void main(String[] args) {
        Cat cat = new Cat("元宝", 10);
        Dog dog = new Dog("小七", 12);

        //线上转型
        Animal animal = cat;
        animal.eat();
        animal = dog;
        animal.eat();

        if(animal instanceof Cat) {
            cat = (Cat)animal;
            cat.eat();
        }
        if(animal instanceof Dog) {
            dog = (Dog)animal;
            dog.eat();
        }
    }
}
